package com.leoman.postapi.service.impl;

import com.leoman.category.dao.CategoryDao;
import com.leoman.category.entity.Category;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.*;
import com.leoman.indexapi.service.UserTaskApiService;
import com.leoman.message.dao.MessageDao;
import com.leoman.message.entity.Message;
import com.leoman.post.dao.*;
import com.leoman.post.entity.*;
import com.leoman.post.entity.vo.*;
import com.leoman.postapi.service.PostService;
import com.leoman.reourceapi.service.impl.ResourceApiServiceImpl;
import com.leoman.systemsetting.dao.HotWordsDao;
import com.leoman.systemsetting.entity.HotWords;
import com.leoman.systemsetting.entity.UserTask;
import com.leoman.user.dao.UserAttentionDao;
import com.leoman.user.dao.UserCollectDao;
import com.leoman.user.dao.UserInfoDao;
import com.leoman.user.entity.UserAttention;
import com.leoman.user.entity.UserCollect;
import com.leoman.user.entity.UserInfo;
import com.leoman.userapi.service.UserIntegralService;
import com.leoman.userchange.dao.UserChangeDao;
import com.leoman.userchange.entity.UserChange;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.SmsSendUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 帖子
 * Created by Administrator on 2016/6/12.
 */
@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostImageDao postImageDao;

    @Autowired
    private PostCommentDao postCommentDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private PostBaseDao postBaseDao;

    @Autowired
    private UserChangeDao userChangeDao;

    @Autowired
    private UserAttentionDao userAttentionDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private TpPostUserDao tpPostUserDao;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private UserTaskApiService userTaskApiService;

    @Autowired
    private CommentPraiseDao commentPraiseDao;

    @Autowired
    private TpPostSubDao tpPostSubDao;

    @Autowired
    private ZbPostInfoDao zbPostInfoDao;

    @Autowired
    private HotWordsDao hotWordsDao;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private MessageDao messageDao;

    @Override
    @Transactional
    public void saveUserPost(MultipartRequest multipartRequest, Long userId, Long category, String content, Integer voiceLength, Integer imgCount) throws ParamsErrorException, UserSpeakErrorException {
        PostBase postBase = new PostBase();

        try {
            // 保存用户帖基本信息
            UserInfo userInfo = userInfoDao.findOne(userId);

            if (null != userInfo && userInfo.getStatus().equals(Constant.USER_STATUS_GAG)) {
                throw new UserSpeakErrorException();
            }

            // 保存图片和语音
            if (userInfo.getIsCreator() == 1 || userInfo.getLevel() > 4) {
                MultipartFile voice = multipartRequest.getFile("voice");
                if (null != voice) {
                    FileBo voiceFile = FileUtil.save(voice, false);
                    postBase.setUrl(voiceFile.getPath());
                    postBase.setLength(voiceLength);
                }
            }

            postBase.setUserInfo(userInfo);
            postBase.setContent(content);
            postBase.setName(content);
            postBase.setType(Constant.POST_TYPE_003);

            Category category1 = categoryDao.findOne(category);

            if (null == category1) {
                throw new ParamsErrorException();
            }

            category1.setCount(category1.getCount() + 1);
            categoryDao.save(category1);

            postBase.setCategory(category1);
            postBase.setPraise(0);
            postBase.setComment(0);
            postBase.setCreateDate(System.currentTimeMillis());
            postBase.setStatus(0);

            // 周为说的
            /*if (userInfo.getIsCreator().equals(Constant.IF_CREATOR_YES)) {
                postBase.setIsCreator(Constant.IF_CREATOR_YES);
            }*/

            postBaseDao.save(postBase);

            List<MultipartFile> list = new ArrayList<>();

            if (null != imgCount) {
                MultipartFile multipartFile;
                for (int i = 0; i < imgCount; i++) {
                    multipartFile = multipartRequest.getFile("file" + i);
                    list.add(multipartFile);
                }
            } else {
                list = multipartRequest.getFiles("file");
            }

            FileBo imageFile;
            PostImage postImage;
            for (MultipartFile file : list) {
                if (null != file && file.getSize() > 0) {
                    imageFile = FileUtil.saveNoThumb(file);
                    postImage = new PostImage();
                    postImage.setPostId(postBase.getId());
                    postImage.setType(Constant.POST_TYPE_003);
                    postImage.setUrl(imageFile.getPath());
                    postImage.setSuolue(imageFile.getSuoluePath());
                    postImage.setHeight(imageFile.getHeight());
                    postImage.setWidth(imageFile.getWidth());

                    postImageDao.save(postImage);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 进行每日发帖子任务
        userTaskApiService.finishTask(userId, Constant.USER_TASK_TYPE_004, false);

        userTaskApiService.addPostPlayNum(postBase, 0, 1);
    }

    @Override
    public void saveZbPost(MultipartRequest multipartRequest, Long userId, Long postId, String content, Integer voiceLength, Integer imgCount) throws ParamsErrorException, PostNotFindException, UserSpeakErrorException {
        PostBase postBase = null;

        try {
            if (null == userId || null == postId) {
                throw new ParamsErrorException();
            }

            // 保存用户帖基本信息
            postBase = postBaseDao.findOne(postId);

            if (null == postBase) {
                throw new PostNotFindException();
            }

            UserInfo userInfo = userInfoDao.findOne(userId);

            if (userInfo.getStatus().equals(Constant.USER_STATUS_GAG)) {
                throw new UserSpeakErrorException();
            }

            ZbPostInfo zbPostInfo = new ZbPostInfo();
            zbPostInfo.setPostBase(postBase);
            zbPostInfo.setAvater(userInfo.getAvater());
            zbPostInfo.setNickname(userInfo.getNickname());
            zbPostInfo.setContent(content);

            // 保存图片和语音
            MultipartFile voice = multipartRequest.getFile("voice");
            if (null != voice) {
                FileBo voiceFile = FileUtil.save(voice, false);
                zbPostInfo.setUrl(voiceFile.getPath());
                zbPostInfo.setLength(voiceLength);
            }

            zbPostInfoDao.save(zbPostInfo);

            List<MultipartFile> list = new ArrayList<>();

            if (null != imgCount) {
                MultipartFile multipartFile;
                for (int i = 0; i < imgCount; i++) {
                    multipartFile = multipartRequest.getFile("file" + i);
                    System.out.println("图片数量：" + (i + 1));
                    list.add(multipartFile);
                }
            } else {
                list = multipartRequest.getFiles("file");
            }

            FileBo imageFile;
            PostImage postImage;
            for (MultipartFile file : list) {
                if (null != file && file.getSize() > 0) {
                    imageFile = FileUtil.saveNoThumb(file);
                    postImage = new PostImage();
                    postImage.setPostId(zbPostInfo.getId());
                    postImage.setType(Constant.POST_TYPE_001);
                    postImage.setUrl(imageFile.getPath());
                    postImage.setSuolue(imageFile.getSuoluePath());
                    postImage.setHeight(imageFile.getHeight());
                    postImage.setWidth(imageFile.getWidth());

                    postImageDao.save(postImage);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        userTaskApiService.addPostPlayNum(postBase, 0, 1);
    }

    @Override
    public void deletePost(Long postId) throws PostNotFindException {
        PostBase postBase = postBaseDao.findOne(postId);
        if (null == postBase || postBase.getDeleteStatus() == 1) {
            throw new PostNotFindException();
        }

        postBase.setDeleteStatus(1);
        postBaseDao.save(postBase);
    }

    @Override
    @Transactional
    public void savePostComment(MultipartRequest multipartRequest, Integer type, Long postId, Long userId, String content) throws UserSpeakErrorException {
        UserInfo localUser = userInfoDao.findOne(userId);

        if (localUser.getStatus().equals(Constant.USER_STATUS_GAG)) {
            throw new UserSpeakErrorException();
        }

        PostBase postBase = postBaseDao.findOne(postId);
        PostComment postComment = new PostComment();
        postComment.setPostBase(postBase);
        postComment.setFromUser(localUser);
        postComment.setType(type);
        postComment.setContent(content);
        postComment.setStatus(Constant.COMMENT_TYPE_DEFAULT);

        postCommentDao.save(postComment);

        // 增加评论图片
        addPostImages(multipartRequest, postComment.getId());

        // 增加评论数
        postBase.setComment(postBase.getComment() + 1);

        // 发布的帖子被主创评论获得4经验值
        /*if (type.equals(Constant.POST_TYPE_003) && userInfo.getIsCreator() == 1) {
            userInfo = postBase.getUserInfo();
            userIntegralService.changeIntegral(userInfo, "发布的帖子被主创评论获得4经验值", 4);
        }*/

        // 如果是主创，修改帖子的主创参与状态
        if (!localUser.getIsCreator().equals(0)) {
            postBase.setIsCreator(1);
        }

        postBaseDao.save(postBase);

        // 进行每日评论帖子任务
        userTaskApiService.finishTask(userId, Constant.USER_TASK_TYPE_003, false);

        // 发评论可获得5经验值，每日最多获得20经验值
        UserTask userTask = userTaskApiService.findInfoByUserIdAndType(userId, Constant.USER_TASK_TYPE_003);
        if (userTask.getCount() <= 5) {
            userIntegralService.changeIntegral(localUser, "发评论可获得20经验值", 20);
        }
    }

    private void addPostImages(MultipartRequest multipartRequest, Long postCommentId) {
        // 增加评论图片
        PostImage postImage;
        List<MultipartFile> multipartFiles = multipartRequest.getFiles("images");
        try {
            FileBo fileBo;

            for (MultipartFile multipartFile : multipartFiles) {
                if (null == multipartFile || multipartFile.getSize() == 0) {
                    continue;
                }

                fileBo = FileUtil.save(multipartFile, true);

                postImage = new PostImage();
                postImage.setPostId(postCommentId);
                postImage.setType(Constant.POST_TYPE_004);
                postImage.setUrl(fileBo.getPath());
                postImage.setSuolue(fileBo.getSuoluePath());
                postImage.setHeight(fileBo.getHeight());
                postImage.setWidth(fileBo.getWidth());

                postImageDao.save(postImage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Page<PostBase> iPage(String key, Long targetUserId, Long category, Long userId, Integer pageNum, Integer pageSize) throws ParamsErrorException {
        if (null == pageNum || null == pageSize) {
            throw new ParamsErrorException();
        }

        if (StringUtils.isNotEmpty(key)) {
            // 查询有没有当前热词，如果有，搜索次数加1；
            // 如果没有，新增一条热词记录
            HotWords hotWords = hotWordsDao.findOneByContent(key);
            if (null == hotWords) {
                hotWords = new HotWords();
                hotWords.setContent(key);
                hotWords.setCount(0);
                hotWordsDao.save(hotWords);
            } else {
                hotWords.setCount(hotWords.getCount() + 1);
            }
            hotWordsDao.save(hotWords);

            key = "%" + key + "%";
        } else {
            key = "%%";
        }

        Page<PostBase> page;
        if (!key.equals("%%")) {
            page = postBaseDao.iPageDesc(key, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "stick", "createDate"));
        } else {
            if (null == targetUserId) {
                // 热门帖子
                if (null == category || category == 0) {
                    if (null == userId) {
                        page = postBaseDao.iPageDesc(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "stick", "id"));
                    } else {
                        page = postBaseDao.iPageDesc2(userId, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "stick", "id"));
                    }
                } else {
                    page = postBaseDao.iPageByCategory(category, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "essence", "stick", "id"));
                }
            } else {
                // 获取我的帖子列表
                if (null == category) {
                    page = postBaseDao.iPageMyPost(targetUserId, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "stick", "id"));
                } else {
                    page = postBaseDao.iPageMyPostParams(category, targetUserId, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "stick", "id"));
                }
            }
        }


        for (PostBase postBase : page.getContent()) {
            getPostBaseInfo(postBase, userId, 0);
            if (postBase.getType().equals(Constant.POST_TYPE_003)) {
                if (null == postBase.getImageList() || postBase.getImageList().size() == 0) {
                    postBase.setAvater("");
                } else if (postBase.getImageList().size() == 1) {
                    postBase.setAvater(ImageUtil.clearUploadUrl(postBase.getImageList().get(0).getUrl()));
                } else {
                    postBase.setAvater(ImageUtil.clearUploadUrl(postBase.getImageList().get(0).getSuolue()));
                }
            } else {
                postBase.setAvater(StringUtils.isNotEmpty(postBase.getSuolue()) ? ImageUtil.clearUploadUrl(postBase.getSuolue()) : "");
            }
        }

        return page;
    }

    @Override
    public PostBase findOneById(Long postId, Long userId) throws ParamsErrorException, PostNotFindException {
        if (null == postId) {
            throw new ParamsErrorException();
        }

        PostBase postBase = postBaseDao.findOne(postId);
        if (null == postBase || postBase.getDeleteStatus().equals(Constant.POST_STATUS_001)) {
            throw new PostNotFindException();
        }

        getPostBaseInfo(postBase, userId, 1);
        if (!postBase.getType().equals(Constant.POST_TYPE_003)) {
            postBase.setAvater(StringUtils.isNotEmpty(postBase.getAvater()) ? ImageUtil.clearUploadUrl(postBase.getAvater()) : "");
        }

        // 增加该帖子分类的浏览量
        userTaskApiService.addPostPlayNum(postBase, 1, 0);

        return postBase;
    }

    private PostBase getPostBaseInfo(PostBase postBase, Long userId, Integer flag) {
        switch (postBase.getType()) {
            case 1:
                postBase.setZbSubList(getZbPostInfo(postBase.getId()));
                break;
            case 2:
                postBase.setTpPostSubList(getTpPostSubList(postBase.getId(), userId));
                break;
        }

        postBase.setUser(getPostUserPlusVo(postBase.getUserInfo(), userId));
        postBase.setImageList(getPostImageVo(postImageDao.findList(postBase.getId(), postBase.getType()), flag));
        postBase.setUserList(getPostUserVo(userChangeDao.findList(postBase.getId(), Constant.USER_CHANGE_TYPE_001)));
        List<PostComment> list = postCommentDao.findList(postBase.getType(), postBase.getId());
        postBase.setCommentList(getPostCommentVo(list));
        postBase.setComment(list.size());
        postBase.setUrl(StringUtils.isNotEmpty(postBase.getUrl()) ? ImageUtil.clearUploadUrl(postBase.getUrl()) : "");
        List<UserChange> userChangeList = userChangeDao.findListByParams(userId, postBase.getId(), Constant.USER_CHANGE_TYPE_001);
        postBase.setIsPraise(null == userChangeList || userChangeList.size() == 0 ? 0 : 1);
        List<UserCollect> userCollectList = userCollectDao.findListByParams(userId, postBase.getId(), Constant.COLLECT_TYPE_004);
        postBase.setIsCollect(null == userCollectList || userCollectList.size() == 0 ? 0 : 1);
        if (StringUtils.isNotBlank(postBase.getContent())) {
            postBase.setContent(postBase.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));
        }

        return postBase;
    }

    @Override
    public Page<PostCommentVo> commentPage(Integer type, Long postId, final Long userId, Integer pageNum, Integer pageSize) {
        int[] info = ResourceApiServiceImpl.changePageParams(pageNum, pageSize);
        final Page<PostComment> postCommentPage = postCommentDao.iPage(type, postId, new PageRequest(info[0] - 1, info[1]));
        return new Page<PostCommentVo>() {
            @Override
            public int getNumber() {
                return postCommentPage.getNumber();
            }

            @Override
            public int getSize() {
                return postCommentPage.getSize();
            }

            @Override
            public int getTotalPages() {
                return postCommentPage.getTotalPages();
            }

            @Override
            public int getNumberOfElements() {
                return postCommentPage.getNumberOfElements();
            }

            @Override
            public long getTotalElements() {
                return postCommentPage.getTotalElements();
            }

            @Override
            public boolean hasPreviousPage() {
                return postCommentPage.hasPreviousPage();
            }

            @Override
            public boolean isFirstPage() {
                return postCommentPage.isFirstPage();
            }

            @Override
            public boolean hasNextPage() {
                return postCommentPage.hasNextPage();
            }

            @Override
            public boolean isLastPage() {
                return postCommentPage.isLastPage();
            }

            @Override
            public Pageable nextPageable() {
                return postCommentPage.nextPageable();
            }

            @Override
            public Pageable previousPageable() {
                return postCommentPage.previousPageable();
            }

            @Override
            public Iterator<PostCommentVo> iterator() {
                final Iterator<PostComment> postCommentIterator = postCommentPage.iterator();
                return new Iterator<PostCommentVo>() {
                    @Override
                    public boolean hasNext() {
                        return postCommentIterator.hasNext();
                    }

                    @Override
                    public PostCommentVo next() {
                        return getPostCommentVo(postCommentIterator.next(), userId, 0);
                    }
                };
            }

            @Override
            public List<PostCommentVo> getContent() {
                List<PostComment> postCommentList = postCommentPage.getContent();
                List<PostCommentVo> list = new ArrayList<>();

                for (PostComment postComment : postCommentList) {
                    list.add(getPostCommentVo(postComment, userId, 0));
                }

                return list;
            }

            @Override
            public boolean hasContent() {
                return postCommentPage.hasContent();
            }

            @Override
            public Sort getSort() {
                return postCommentPage.getSort();
            }
        };
    }

    @Override
    @Transactional
    public void savePostReply(MultipartRequest multipartRequest, Long postCommentId, Long userId, String content) throws ParamsErrorException, UserSpeakErrorException, CommentNotFindException {
        if (null == postCommentId || null == userId || !StringUtils.isNotEmpty(content)) {
            throw new ParamsErrorException();
        }

        UserInfo userInfo = userInfoDao.findOne(userId);
        if (userInfo.getStatus().equals(Constant.USER_STATUS_GAG)) {
            throw new UserSpeakErrorException();
        }

        PostComment postComment = postCommentDao.findOne(postCommentId);
        if (null == postComment) {
            throw new CommentNotFindException();
        }

        try {
            PostComment tempPostComment = new PostComment();
            tempPostComment.setPostBase(postComment.getPostBase());
            tempPostComment.setFromUser(userInfoDao.findOne(userId));
            tempPostComment.setToPostCommentId(postComment.getId());
            tempPostComment.setToUser(postComment.getFromUser());
            tempPostComment.setType(postComment.getType());
            tempPostComment.setContent(content);
            tempPostComment.setStatus(Constant.COMMENT_TYPE_REPLY);

            postCommentDao.save(tempPostComment);

            // 增加评论图片
            addPostImages(multipartRequest, tempPostComment.getId());

            if (!userInfo.getIsCreator().equals(0)) {
                PostBase postBase = postComment.getPostBase();
                postBase.setIsCreator(1);
                postBaseDao.save(postBase);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void reward(Long creatorUserId, Long userId, Integer count, Long postId) throws ParamsErrorException, CreatorNotFindException, UserSpeakErrorException, BreadShortException, PostNotFindException {
        if (null == creatorUserId || null == userId || null == count) {
            throw new ParamsErrorException();
        }

        UserInfo userInfo = userInfoDao.findOne(userId);
        if (userInfo.getStatus().equals(Constant.USER_STATUS_GAG)) {
            throw new UserSpeakErrorException();
        }

        if (userInfo.getCoin() < count) {
            throw new BreadShortException();
        }

        UserInfo creatorInfo = userInfoDao.findOne(creatorUserId);

        if (null == creatorInfo) {
            throw new CreatorNotFindException();
        }

        userIntegralService.changeCoin(userInfo, "打赏馒头", count * -1);
        userIntegralService.changeCoin(creatorInfo, "被用户打赏馒头", count);

        // 被打赏用户增加被打赏记录
        Message message = new Message();
        message.setTitle("被用户打赏馒头");
        message.setToObject("1");
        message.setContent(userInfo.getNickname() + "打赏你" + count + "个馒头");
        message.setSendDate(System.currentTimeMillis());
        message.setUserId(creatorInfo.getId());
        message.setType(1);

        if (null != postId) {
            PostBase postBase = postBaseDao.findOne(postId);

            if (null == postBase || postBase.getDeleteStatus().equals(Constant.POST_STATUS_001)) {
                throw new PostNotFindException();
            }

            message.setPostId(postId);
        }

        messageDao.save(message);

        // 被打赏用户接收极光推送消息
        List<UserInfo> list = new ArrayList<>();
        list.add(creatorInfo);
        SmsSendUtils.sendJPushMsg(list, System.currentTimeMillis(), message.getContent());
    }

    @Override
    @Transactional
    public void vote(Long userId, String tpPostSubId) throws ParamsErrorException, UserSpeakErrorException, VoteExistException, LevelIsNotEnoughException {
        if (null == userId || StringUtils.isBlank(tpPostSubId)) {
            throw new ParamsErrorException();
        }

        UserInfo userInfo = userInfoDao.findOne(userId);
        if (userInfo.getStatus().equals(Constant.USER_STATUS_GAG)) {
            throw new UserSpeakErrorException();
        }

        if (userInfo.getLevel() > 1) {
            String[] ids = tpPostSubId.split(",");

            TpPostSub tpPostSub = new TpPostSub();
            TpPostUser tpPostUser;

            for (String id : ids) {
                tpPostSub = tpPostSubDao.findOne(Long.parseLong(id));

                tpPostUser = tpPostUserDao.findOneByParams(Long.parseLong(id), userId);
                if (null != tpPostUser) {
                    throw new VoteExistException();
                }

                tpPostUser = new TpPostUser();
                tpPostUser.setUserInfo(userInfo);
                tpPostUser.setTpPostSub(tpPostSub);

                tpPostUserDao.save(tpPostUser);

                // 修改投票对象的票数
                tpPostSub.setCount(tpPostSub.getCount() + 1);
                tpPostSubDao.save(tpPostSub);
            }

            userTaskApiService.addPostTpSubData(tpPostSub.getPostBase(), userInfo, tpPostSubId);
        } else {
            throw new LevelIsNotEnoughException();
        }
    }

    @Override
    public Page<PostMiniVo> iPageByUserId(Long userId, Integer type, Integer pageNum, Integer pageSize) throws ParamsErrorException, UserNotFindException {
        if (null == userId || null == type) {
            throw new ParamsErrorException();
        }

        int[] info = ResourceApiServiceImpl.changePageParams(pageNum, pageSize);

        if (type == 1) {
            Page<PostComment> page = postCommentDao.iPageByToUserId2(userId, new PageRequest(info[0] - 1, info[1]));
            return getPostMiniByPostComment(page);
        } else {
            Page<UserChange> page = userChangeDao.iPageByParams(userId, Constant.USER_CHANGE_TYPE_001, new PageRequest(info[0] - 1, info[1]));
            return getPostMiniByUserChange(page);
        }
    }

    private PostMiniVo getPostMiniByPostCommentInfo(PostComment postComment) {
        PostMiniVo postMiniVo = new PostMiniVo();
        postMiniVo.setId(postComment.getPostBase().getId());
        postMiniVo.setContent(postComment.getPostBase().getName());
        postMiniVo.setNickname(postComment.getFromUser().getNickname());
        postMiniVo.setAvater(getAvater(postComment.getFromUser()));
        postMiniVo.setType(postComment.getType());
        postMiniVo.setCreateDate(postComment.getCreateDate());

        return postMiniVo;
    }

    private PostMiniVo getPostMiniByUserChangeInfo(UserChange userChange) {
        PostMiniVo postMiniVo = new PostMiniVo();
        postMiniVo.setId(userChange.getPostBase().getId());
        postMiniVo.setContent(userChange.getContent());
        postMiniVo.setNickname(userChange.getUserInfo().getNickname());
        postMiniVo.setAvater(getAvater(userChange.getUserInfo()));
        postMiniVo.setType(userChange.getPostBase().getType());
        postMiniVo.setCreateDate(userChange.getCreateDate());

        return postMiniVo;
    }

    private Page<PostMiniVo> getPostMiniByPostComment(final Page<PostComment> postCommentPage) {
        return new Page<PostMiniVo>() {
            @Override
            public int getNumber() {
                return postCommentPage.getNumber();
            }

            @Override
            public int getSize() {
                return postCommentPage.getSize();
            }

            @Override
            public int getTotalPages() {
                return postCommentPage.getTotalPages();
            }

            @Override
            public int getNumberOfElements() {
                return postCommentPage.getNumberOfElements();
            }

            @Override
            public long getTotalElements() {
                return postCommentPage.getTotalElements();
            }

            @Override
            public boolean hasPreviousPage() {
                return postCommentPage.hasPreviousPage();
            }

            @Override
            public boolean isFirstPage() {
                return postCommentPage.isFirstPage();
            }

            @Override
            public boolean hasNextPage() {
                return postCommentPage.hasNextPage();
            }

            @Override
            public boolean isLastPage() {
                return postCommentPage.isLastPage();
            }

            @Override
            public Pageable nextPageable() {
                return postCommentPage.nextPageable();
            }

            @Override
            public Pageable previousPageable() {
                return postCommentPage.previousPageable();
            }

            @Override
            public Iterator<PostMiniVo> iterator() {
                final Iterator<PostComment> postCommentIterator = postCommentPage.iterator();
                return new Iterator<PostMiniVo>() {
                    @Override
                    public boolean hasNext() {
                        return postCommentIterator.hasNext();
                    }

                    @Override
                    public PostMiniVo next() {
                        return getPostMiniByPostCommentInfo(postCommentIterator.next());
                    }
                };
            }

            @Override
            public List<PostMiniVo> getContent() {
                List<PostComment> postCommentList = postCommentPage.getContent();
                List<PostMiniVo> list = new ArrayList<>();

                for (PostComment postComment : postCommentList) {
                    list.add(getPostMiniByPostCommentInfo(postComment));
                }

                return list;
            }

            @Override
            public boolean hasContent() {
                return postCommentPage.hasContent();
            }

            @Override
            public Sort getSort() {
                return postCommentPage.getSort();
            }
        };
    }

    private Page<PostMiniVo> getPostMiniByUserChange(final Page<UserChange> userChangePage) {
        return new Page<PostMiniVo>() {
            @Override
            public int getNumber() {
                return userChangePage.getNumber();
            }

            @Override
            public int getSize() {
                return userChangePage.getSize();
            }

            @Override
            public int getTotalPages() {
                return userChangePage.getTotalPages();
            }

            @Override
            public int getNumberOfElements() {
                return userChangePage.getNumberOfElements();
            }

            @Override
            public long getTotalElements() {
                return userChangePage.getTotalElements();
            }

            @Override
            public boolean hasPreviousPage() {
                return userChangePage.hasPreviousPage();
            }

            @Override
            public boolean isFirstPage() {
                return userChangePage.isFirstPage();
            }

            @Override
            public boolean hasNextPage() {
                return userChangePage.hasNextPage();
            }

            @Override
            public boolean isLastPage() {
                return userChangePage.isLastPage();
            }

            @Override
            public Pageable nextPageable() {
                return userChangePage.nextPageable();
            }

            @Override
            public Pageable previousPageable() {
                return userChangePage.previousPageable();
            }

            @Override
            public Iterator<PostMiniVo> iterator() {
                final Iterator<UserChange> userChangeIterator = userChangePage.iterator();
                return new Iterator<PostMiniVo>() {
                    @Override
                    public boolean hasNext() {
                        return userChangeIterator.hasNext();
                    }

                    @Override
                    public PostMiniVo next() {
                        return getPostMiniByUserChangeInfo(userChangeIterator.next());
                    }
                };
            }

            @Override
            public List<PostMiniVo> getContent() {
                List<UserChange> userChangeList = userChangePage.getContent();
                List<PostMiniVo> list = new ArrayList<>();

                for (UserChange userChange : userChangeList) {
                    list.add(getPostMiniByUserChangeInfo(userChange));
                }

                return list;
            }

            @Override
            public boolean hasContent() {
                return userChangePage.hasContent();
            }

            @Override
            public Sort getSort() {
                return userChangePage.getSort();
            }
        };
    }

    @Override
    public List<Category> postTypeList() {
        return categoryDao.findType(Constant.CATEGORY_TYPE_001);
    }

    @Override
    public Page<PostBase> iPageByUserCollect(Long userId, Integer pageNum, Integer pageSize) {
        return postBaseDao.iPageByUserCollect(userId, new PageRequest(pageNum - 1, pageSize));
    }

    @Override
    public List<HotWords> iFindList() {
        Page<HotWords> page = hotWordsDao.iPage(new PageRequest(0, 4));
        return page.getContent();
    }

    /**
     * 拼接帖子评论VO类
     */
    private PostCommentVo getPostCommentVo(PostComment postComment, Long userId, Integer flag) {
        PostCommentVo postCommentVo;
        UserInfo userInfo = userInfoDao.findOne(postComment.getFromUser().getId());
        postCommentVo = new PostCommentVo();
        postCommentVo.setId(postComment.getId());
        postCommentVo.setUserId(postComment.getFromUser().getId());
        postCommentVo.setNickname(userInfo.getNickname());
        postCommentVo.setAvater(getAvater(userInfo));
        postCommentVo.setLevel(userInfo.getLevel());
        postCommentVo.setContent(postComment.getContent());
        postCommentVo.setIsCreator(null == postComment.getFromUser().getIsCreator() ? 0 : postComment.getFromUser().getIsCreator());
        postCommentVo.setPraise(commentPraiseDao.findListByParams(postComment.getId(), Constant.COMMENT_PRAISE_TYPE_001, Constant.COMMENT_PRAISE_ISDETAIL_NO).size());
        postCommentVo.setIsPraise(null != commentPraiseDao.findOneByParams(postComment.getId(), userId, Constant.COMMENT_PRAISE_TYPE_001, Constant.COMMENT_PRAISE_ISDETAIL_NO) ? 0 : 1);
        postCommentVo.setCommentImageList(getPostImageVo(postImageDao.findList(postComment.getId(), Constant.POST_TYPE_004), flag));
        postCommentVo.setCreateDate(postComment.getCreateDate());
        if (null != postComment.getToPostCommentId()) {
            PostComment postComment1 = postCommentDao.findOne(postComment.getToPostCommentId());
            if (null != postComment1) {
                postCommentVo.setReplyName(postComment1.getFromUser().getNickname());
                postCommentVo.setReplyContent(postComment1.getContent());
                postCommentVo.setReplyImageList(getPostImageVo(postImageDao.findList(postComment1.getId(), Constant.POST_TYPE_004), flag));
            }
        }

        return postCommentVo;
    }

    /**
     * 拼接帖子图片VO列表
     */
    public static List<PostImageVo> getPostImageVo(List<PostImage> list, Integer flag) {
        List<PostImageVo> postImageVoList = new ArrayList<>();
        PostImageVo postImageVo;

        try {
            for (PostImage postImage : list) {
                postImageVo = new PostImageVo();
                postImageVo.setId(postImage.getId());
                if (flag == 0) {
                    postImageVo.setUrl(ImageUtil.clearUploadUrl(postImage.getSuolue()));
                } else {
                    postImageVo.setUrl(ImageUtil.clearUploadUrl(postImage.getUrl()));
                }
                postImageVo.setHeight(postImage.getHeight());
                postImageVo.setWidth(postImage.getWidth());

                postImageVoList.add(postImageVo);
            }

            if (list.size() == 1 && list.get(0).getType().equals(Constant.POST_TYPE_003)) {
                postImageVoList = new ArrayList<>();
                postImageVo = new PostImageVo();
                postImageVo.setId(list.get(0).getId());
                postImageVo.setUrl(ImageUtil.clearUploadUrl(list.get(0).getUrl()));
                postImageVo.setHeight(list.get(0).getHeight());
                postImageVo.setWidth(list.get(0).getWidth());

                postImageVoList.add(postImageVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return postImageVoList;
    }

    /**
     * 拼接帖子评论VO列表
     *
     * @param list 帖子评论列表
     * @return 帖子评论VO列表
     */
    private List<PostCommentVo> getPostCommentVo(List<PostComment> list) {
        List<PostCommentVo> postCommentVoList = new ArrayList<>();
        List<PostComment> postCommentList = new ArrayList<>();

        if (null == list || list.size() == 0) {
            return postCommentVoList;
        }

        if (list.size() > 3) {
            postCommentList.add(list.get(0));
            postCommentList.add(list.get(1));
            postCommentList.add(list.get(2));

            list = postCommentList;
        }

        PostCommentVo postCommentVo;
        UserInfo userInfo;
        for (PostComment postComment : list) {
            postCommentVo = new PostCommentVo();
            userInfo = userInfoDao.findOne(postComment.getFromUser().getId());
            postCommentVo.setUserId(postComment.getFromUser().getId());
            postCommentVo.setNickname(userInfo.getNickname());
            postCommentVo.setAvater(getAvater(userInfo));
            postCommentVo.setLevel(userInfo.getLevel());
            postCommentVo.setContent(postComment.getContent());
            postCommentVo.setCreateDate(postComment.getCreateDate());

            postCommentVoList.add(postCommentVo);
        }

        return postCommentVoList;
    }

    /**
     * 拼接帖子点赞用户VO类
     *
     * @param list 点赞列表
     * @return 点赞帖子用户列表
     */
    private List<PostUserVo> getPostUserVo(List<UserChange> list) {
        List<PostUserVo> postUserVoList = new ArrayList<>();
        PostUserVo postUserVo;
        UserInfo userInfo;

        try {
            for (UserChange userChange : list) {
                userInfo = userChange.getUserInfo();
                postUserVo = new PostUserVo();
                postUserVo.setId(userInfo.getId());
                postUserVo.setNickname(userInfo.getNickname());
                postUserVo.setAvater(getAvater(userInfo));

                postUserVoList.add(postUserVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return postUserVoList;
    }

    private String getAvater(UserInfo userInfo) {
        if (StringUtils.isEmpty(userInfo.getAvater())) {
            return userInfo.getAvater();
        }
        String head = userInfo.getAvater().replaceAll(Configue.getUploadUrls(), "");
        if (!head.contains("http")) {
            return Configue.getUploadUrls() + head;
        } else {
            return head;
        }
    }

    /**
     * 拼接帖子发布人VO类
     *
     * @param userInfo 用户详情
     * @param userId   用户id
     * @return 发帖人详情
     */
    private PostUserPlusVo getPostUserPlusVo(UserInfo userInfo, Long userId) {
        PostUserPlusVo postUserPlusVo = new PostUserPlusVo();

        postUserPlusVo.setId(userInfo.getId());
        postUserPlusVo.setNickname(userInfo.getNickname());
        // 获取用户头像
        postUserPlusVo.setAvater(getAvater(userInfo));
        postUserPlusVo.setLevel(userInfo.getLevel());
        if (null != userId) {
            UserAttention tempUserAttention = userAttentionDao.findOneInfo(userId, userInfo.getId());
            if (null == tempUserAttention || tempUserAttention.getStatus() == 1) {
                postUserPlusVo.setIsAttention(1);
            } else {
                postUserPlusVo.setIsAttention(0);
            }
        } else {
            postUserPlusVo.setIsAttention(1);
        }
        postUserPlusVo.setIsCreator(null == userInfo.getIsCreator() ? 0 : userInfo.getIsCreator());

        return postUserPlusVo;
    }

    /**
     * 获取投票帖详情列表
     *
     * @param postId 帖子id
     * @param userId 用户id
     * @return 投票帖对象集合
     */
    private List<TpPostSub> getTpPostSubList(Long postId, Long userId) {
        List<TpPostSub> list = postBaseDao.iFindListTP(postId);

        for (TpPostSub tpPostSub : list) {
            tpPostSub.setCover(ImageUtil.clearUploadUrl(tpPostSub.getCover()));
            tpPostSub.setStatus(null != tpPostUserDao.findOneByParams(tpPostSub.getId(), userId) ? 0 : 1);
        }

        return list;
    }

    private List<ZbPostInfo> getZbPostInfo(Long postId) {
        List<ZbPostInfo> list = postBaseDao.iFindListZB(postId);
        List<PostImage> imageList;

        for (ZbPostInfo zbPostInfo : list) {
            zbPostInfo.setAvater(ImageUtil.clearUploadUrl(zbPostInfo.getAvater()));
            zbPostInfo.setUrl(ImageUtil.clearUploadUrl(zbPostInfo.getUrl()));

            imageList = postImageDao.findList(zbPostInfo.getId(), Constant.POST_TYPE_001);

            for (PostImage postImage : imageList) {
                postImage.setUrl(ImageUtil.clearUploadUrl(postImage.getUrl()));
                postImage.setSuolue(ImageUtil.clearUploadUrl(postImage.getSuolue()));
            }

            zbPostInfo.setImageList(imageList);
        }

        return list;
    }
}
